<template>
    <div    class="login-container"   >
        <div v-if="welcome"       class="welcome">
               <span class="timer"  @click="finishWelcome" >{{count}}s</span>
               <i></i>
               <span>璇玑智能采购系统</span>
               <em>{{comment[new Date().getMonth()]}}</em>
        </div>

        <div  v-else  class="login-box" >
            <span class="brand"  >璇玑智能采购系统</span>
            <div class="ipt"    >
                <input type="text" placeholder="请输入手机号" v-model.trim="loginObject.phone">
            </div>
            <div  class="ipt  lock" >
                <input     type="text" placeholder="请输入验证码"  v-model="loginObject.vdtCode">
                <span  @click="getVdtCode" >{{ vdtText }}</span>
            </div>
            <van-checkbox v-model="remember"  >是否记住手机号?</van-checkbox>
            <van-checkbox v-model="auto"   >是否7天免登录?</van-checkbox>
            <van-button  block   type = 'info'  @click="loginEvt"  >登录</van-button>
        </div>   

        <span class="right"   >power by 用友川分科技&copy;2023-01</span>
    </div>
</template>

<script>

    import {autoLoginApi, getVdtCodeApi, loginApi, userInfoApi} from '../../apis/userApi'
    export default {
           data (){
            return  {
                 comment:[
                    '渐寒揣着喜庆的年',
                    '情迷有巧克力芬芳',
                    '微暖花出豆蔻意浅',
                    '鹅黄林徽因的晴天',
                    '初夏送了春的婉转',
                    '离殇一曲青春飞扬',
                    '炎炎宛若你的张狂',
                    '芬芳桂花羹与蜜糖',
                    '旖旎谁与谁的迷藏',
                    '枫红灼了彷徨的眼',
                    '寒入思念如雪飞扬',
                    '弥彰假装遗忘的慌'
                 ],
                 count:5,
                 countTimer:null,
                 welcome:true,
                 remember:false,
                 auto:false,

                 //定义一个免登录标志
                 autoLogin:false,
                
                 //登录接口需要用到的数据参数
                 loginObject:{
                    phone:'',
                    vdtCode:''
                 },
                 //  获取验证码的文字
                 vdtText:'获取验证码'
            }
           },


          created(){

            // 3、缓存中拿出手机号，并勾选上，赋值

            let  phone = localStorage.getItem('user-phone')
               
            if(!!phone){
                this.loginObject.phone = phone
                this.remember = true
            }
             // 1、启动定时器
             this.startTimer(Date.now())
             //2、 免登录业务
             
              this.autoLoginEvt()
            
              

          },
         
          methods: {
               startTimer(st){
                  
              this.countTimer =  setTimeout(()=>{
                    this.count = Math.ceil(5 - (Date.now() - st ) / 1000)
                    if(this.count > 0){
                        this.startTimer(st)
                    }else{
                        clearTimeout(this.countTimer)
                      this.handleWelcomeEvt()
                    }
                },200)
               }, 
               
        
               finishWelcome(){
                
               // if(!this.autoLogin)  return  这句代码可以不要
             
                  clearTimeout(this.countTimer)
                // 根据免登录的结果来做业务
               
                this.handleWelcomeEvt()
               },


                 //处理免登录业务结果的一个方法
                 handleWelcomeEvt() {
              
                let user = this.$store.getters['common/userInfo']
                if (!!user.id) {
                    this.$router.push('/home')
                } else {
                    this.welcome = false
                }
            },
                    // 1、免登录业务
           async   autoLoginEvt(){
                let  cache = localStorage.getItem("auto-token")
          
                   //console.log(cache)
                if(!cache){
                    this.autoLogin= true
                    return
                }
              
                this.$store.commit('common/mutationToken',cache)
               
                // 调用免登录接口
             
                  let  result   =  await  autoLoginApi()
              
                  this.autoLogin = true

                  //免登陆接口调用失败
                   if( result.code !== 200 ){
                       localStorage.removeItem("auto-token")
                        return
                   } 

                   //缓存用户信息
                this.$store.commit('common/mutationUserInfo',result.data) 
           },
           
                   
              
               //2、登录业务

                async getVdtCode(){
                     
                        //校验手机号是否正确
                    if( !/^1[3-9]{1}[0-9]{9}$/.test(this.loginObject.phone)){
                          this.$toast({message:'请输入正确手机号',position:'bottom'})
                          return
                        
                    }
                    
                    // 把验证码的文字变为动态的，点击发送请求文字变为：‘重新获取验证码 Xs ’，倒计时处理，并做节流优化
                       if(this.vdtText !== '获取验证码') return
                       this.vdtText = '获取验证码'
                       
                       let result  = await  getVdtCodeApi(this.loginObject.phone)
                        
                       if(result.code !== 200){
                           this.$toast.fail('获取验证码失败，请重试')
                           return
                       }
                       // 提示用户验证码，并提示再次获取验证码的时间

                       this.$toast.success(`验证码:${result.data.vdtCode}`)

                       this.vdtTimeLoop(Date.now())

                       
                },

                vdtTimeLoop(st){
                     setTimeout(()=>{
                        let  _timer = Math.ceil(60 - (Date.now() - st)/1000)
                             if(_timer > 0){
                                this.vdtText = `再次获取(${_timer}s)`
                                this.vdtTimeLoop(st)
                             }else{
                                this.vdtText="获取验证码"
                             }
                     },200)
                },


                async  loginEvt (){
                        //校验手机号是否正确
                        if( !/^1[3-9]{1}[0-9]{9}$/.test(this.loginObject.phone)){
                          this.$toast({message:'请输入正确手机号',position:'bottom'})
                          return
                        
                    }

                    // 效验验证码

                    if(isNaN(this.loginObject.vdtCode) || this.loginObject.vdtCode.length !==  4   ){
                        
                        this.$toast({message:'请输入正确验证码',position:'bottom'})
                         return
                    }
                     

                    let toast = this.$toast.loading({
                        message: '登录中...',
                        forbidClick: true,
                        loadingType: 'spinner',
                    })
                     

                    let result  = await loginApi(this.loginObject)
                    if(result.code !== 200){
                         toast.clear()
                         this.$toast.fail('用户登录失败，请重试')
                         return

                    }

                    //  根据登录接口返回的数据，拿到token，缓存到vuex中 ,紧接着调用获去用户信息接口，同样也缓存到vuex中

                    this.$store.commit('common/mutationToken',result.data.token)
                 
                    let user = await userInfoApi(result.data.id)
               
                    if(user.code === 200){
                        this.$store.commit('common/mutationUserInfo',user.data)
                        
                    }


                    //  是否勾选记住手机号
                    if(this.remember){
                        localStorage.setItem('user-phone',this.loginObject.phone)
                    }else{
                        localStorage.removeItem('user-phone')
                    }

                    //是否7天免登录
                    if(this.auto){
                        localStorage.setItem("auto-token",result.data.token)
                    }else{
                        localStorage.removeItem('auto-token')
                    }
                  // 关闭加载框.跳转到首页
                  toast.clear()
                  this.$router.push('/home')
                }
       
                   
           }





    }
</script>

<style  scoped   lang="less"  >
     @import './index.less';
      
</style>